/*
 * Copyright (C) 2009 Rafael Fernandes
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.phonebooksharing.android.activities.privacy;

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.CheckedTextView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

import com.phonebooksharing.android.R;
import com.phonebooksharing.android.widgets.header.ListWithHeaderListAdapter;
import com.phonebooksharing.android.widgets.scroll.HorizontalScroller;

import dalvik.system.VMRuntime;

public class PrivacyGroupSetupActivity extends Activity implements View.OnLongClickListener {
	
	public static final String ID = "i",
	                           POSITION = "po",
	                           TITLE = "t",
	                           GRANT_GROUPS = "gg",
	                           CONTACT_PRIVACY_CHOSEN = "p",
	                           IMAGE_PRIVACY_CHOSEN = "ip",
	                           VIDEO_PRIVACY_CHOSEN = "vp",
	                           POSTCARD_PRIVACY_CHOSEN = "pp",
	                           WISH_LIST_PRIVACY_CHOSEN = "wp";
	
	private int groupID, position;
	
	private HorizontalScroller hs;
	
	public static final String[][] PRIVACY_OPTIONS = new String[][]{
		{"All My Contacts", 		"Members can see all my contacts with no restrictions"},
		{"This Group", 				"Members can see only contacts on this group"},
//		{"Network Group", 			"Members of this group and their first connections"},
		{"Grant Specific Groups", 	"Specify which groups they are allowed to see"},//must be previous of last
		{"None of My Contacts (invisible)", 	"Members can not see my contacts"},
	};
	
	public static final String[][] GALLERY_PRIVACY_OPTIONS = new String[][]{
        {"All",                  "Members can see all image gallery with no restrictions"},
        {"None (invisible)",     "Members can not see my image gallery"},
    };
	
	private long oldHeapSize;
	
	private int contactPrivacy  = -1,
	            imagePrivacy    = -1,
	            videoPrivacy    = -1,
	            postCardPrivacy = -1,
	            wishListPrivacy = -1;
	
	@Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        
     // Eliminate extra GCs during startup by setting the initial heap size to 4MB.
        oldHeapSize = VMRuntime.getRuntime().setMinimumHeapSize(4*1024*1024);
        setContentView(R.layout.privacy_group_setup);
        
        hs = (HorizontalScroller) findViewById(R.id.scroller);
        hs.setOnLongClickListener(this);
        
        Intent i = getIntent();
        ((TextView)findViewById(android.R.id.text1)).setText(i.getStringExtra(TITLE) + "'s Privacy");
        ((TextView)findViewById(android.R.id.text2)).setText("Here you setup the visibility of this group. In other words:\nMembers of this group can see/navigate:");

        groupID = i.getIntExtra(ID, -1);
        position = i.getIntExtra(POSITION, -1); 
        
        addContactList();
        addGalleryList("Image Gallery's Privacy", new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                imagePrivacy = position - 1;//minus header
            }
        });
        addGalleryList("Video Gallery's Privacy", new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                videoPrivacy = position - 1;//minus header
            }
        });
        
        addGalleryList("PostCard Gallery's Privacy", new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                postCardPrivacy = position - 1;//minus header
            }
        });
        
        addGalleryList("Wish List's Privacy", new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                wishListPrivacy = position - 1;//minus header
            }
        });
	}
	
	private void addContactList() {
	    final ListView lv = new ListView(this);
        lv.setItemsCanFocus(false);
        lv.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        
        ListWithHeaderListAdapter adapter = new ListWithHeaderListAdapter(this);
        adapter.addSection("Contact List's Privacy", new ContactPrivacyAdapter(this));

        lv.setAdapter(adapter);
        
        lv.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                contactPrivacy = position;
                if (position == (PRIVACY_OPTIONS.length - 1)) {
                    Intent i = new Intent(PrivacyGroupSetupActivity.this, PrivacyGroupSelectionActivity.class);
                    i.putExtra(PrivacyGroupSelectionActivity.ID, groupID);
                    startActivityForResult(i, 0);// TODO: check if there is a selection
                }
            }
        });
        
        hs.addView(lv);
    }
	
	private void addGalleryList(String gallery, OnItemClickListener listener) {
        final ListView lv = new ListView(this);
        lv.setItemsCanFocus(false);
        lv.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        
        ListWithHeaderListAdapter adapter = new ListWithHeaderListAdapter(this);
        adapter.addSection(gallery, new GalleryPrivacyAdapter(this));

        lv.setOnItemClickListener(listener);
        
        lv.setAdapter(adapter);
        hs.addView(lv);
    }

    private ArrayList<Integer> selectedGroups;
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		
		selectedGroups = data.getIntegerArrayListExtra(GRANT_GROUPS);
	}
	
	@Override
    protected Dialog onCreateDialog(int id) {
        return new AlertDialog.Builder(this)
        .setIcon(android.R.drawable.ic_dialog_alert)
        .setTitle("Setup Not Completed")
        .setMessage("You can flip to the next screens or use the menu to complete the setup\n\nWould you like to close anyway?")
        .setPositiveButton("Back to Setup", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                //nothing here
            }
        })
        .setNegativeButton("Close", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                canClose = true;
                finish();
            }
        })
        .create();
    }

	private boolean canClose = false;
	
    @Override
	public void finish() {
        
        if(contactPrivacy >= 0 &&
           imagePrivacy >=0 &&
           videoPrivacy >= 0 &&
           postCardPrivacy >= 0 &&
           wishListPrivacy >= 0) {
           
            canClose = true;
        } else {
            showDialog(0);
        }
        
		final Intent i = new Intent();
		i.putExtra(GRANT_GROUPS,             selectedGroups);
		i.putExtra(ID,                       groupID);
		i.putExtra(POSITION,                 position);
		i.putExtra(CONTACT_PRIVACY_CHOSEN,   contactPrivacy);
		i.putExtra(IMAGE_PRIVACY_CHOSEN,     imagePrivacy);
        i.putExtra(VIDEO_PRIVACY_CHOSEN,     videoPrivacy);
        i.putExtra(POSTCARD_PRIVACY_CHOSEN,  postCardPrivacy);
        i.putExtra(WISH_LIST_PRIVACY_CHOSEN, wishListPrivacy);
		setResult(RESULT_OK, i);
		
        if(canClose) {
            super.finish();
        }
	}

//	@Override
//    protected void onListItemClick(ListView l, View v, int position, long id) {
//		super.onListItemClick(l, v, position, id);
//		
//		if(position == (PRIVACY_OPTIONS.length - 2)) {
//			Intent i = new Intent(this, PrivacyGroupSelectionActivity.class);
//			i.putExtra(PrivacyGroupSelectionActivity.ID, groupID);
//			startActivityForResult(i, 0);//TODO: check if there is a selection
//		}
//	}
	
	static class ContactPrivacyAdapter extends BaseAdapter {
        private LayoutInflater inflater;

        public ContactPrivacyAdapter(Context c) {
            this.inflater = LayoutInflater.from(c);
        }

        public int getCount() {
            return PRIVACY_OPTIONS.length;
        }

        public Object getItem(int position) {
            return position;
        }

        public long getItemId(int position) {
            return position;
        }
        
        public View getView(int position, View cv, ViewGroup parent) {
        	ViewHolder holder;
            if(cv == null) {
                cv = inflater.inflate(R.layout.check_list_item_2line, parent, false);
                holder = new ViewHolder();
//                holder.icon1    = (ImageView)cv.findViewById(android.R.id.icon1);
                holder.checkbox = (CheckedTextView)cv.findViewById(android.R.id.checkbox);
                holder.text1    = (TextView)cv.findViewById(android.R.id.title);
                holder.text2    = (TextView)cv.findViewById(android.R.id.summary);

                cv.setTag(holder);
            } else {
                holder = (ViewHolder)cv.getTag();
            }
            
            final String[] s = PRIVACY_OPTIONS[position];
            holder.text1.setText(s[0]);
            holder.text2.setText(s[1]);
//            holder.icon1.setVisibility(View.GONE);
            holder.checkbox.setVisibility(View.VISIBLE);
            
            return cv;
        }
        
        static class ViewHolder {
//        	ImageView icon1;
        	CheckedTextView checkbox;
        	TextView text1, text2;
        }
    }

    static class GalleryPrivacyAdapter extends BaseAdapter {
        private LayoutInflater inflater;

        public GalleryPrivacyAdapter(Context c) {
            this.inflater = LayoutInflater.from(c);
        }

        public int getCount() {
            return GALLERY_PRIVACY_OPTIONS.length;
        }

        public Object getItem(int position) {
            return position;
        }

        public long getItemId(int position) {
            return position;
        }
        
        public View getView(int position, View cv, ViewGroup parent) {
            ViewHolder holder;
            if(cv == null) {
                cv = inflater.inflate(R.layout.check_list_item_2line, parent, false);
                holder = new ViewHolder();
//                holder.icon1    = (ImageView)cv.findViewById(android.R.id.icon1);
                holder.checkbox = (CheckedTextView)cv.findViewById(android.R.id.checkbox);
                holder.text1    = (TextView)cv.findViewById(android.R.id.title);
                holder.text2    = (TextView)cv.findViewById(android.R.id.summary);

                cv.setTag(holder);
            } else {
                holder = (ViewHolder)cv.getTag();
            }
            
            final String[] s = GALLERY_PRIVACY_OPTIONS[position];
            holder.text1.setText(s[0]);
            holder.text2.setText(s[1]);
//            holder.icon1.setVisibility(View.GONE);
            holder.checkbox.setVisibility(View.VISIBLE);
            
            return cv;
        }
        
        static class ViewHolder {
//          ImageView icon1;
            CheckedTextView checkbox;
            TextView text1, text2;
        }
    }
    
    @Override
    public boolean onLongClick(View v) {
        // User long pressed on an item
        return true;
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        hs = null;
        VMRuntime.getRuntime().setMinimumHeapSize(oldHeapSize);
    }
}
